{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table class=\"ee-notebook-buttons\" align=\"left\">\n",
    "    <td><a target=\"_blank\"  href=\"https://github.com/giswqs/geemap/tree/master/tutorials/Image/05_conditional_operations.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n",
    "    <td><a target=\"_blank\"  href=\"https://nbviewer.jupyter.org/github/giswqs/geemap/blob/master/tutorials/Image/05_conditional_operations.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n",
    "    <td><a target=\"_blank\"  href=\"https://colab.research.google.com/github/giswqs/geemap/blob/master/tutorials/Image/05_conditional_operations.ipynb\"><img width=26px src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Relational, conditional and Boolean operations\n",
    "To perform per-pixel comparisons between images, use relational operators. To extract urbanized areas in an image, this example uses relational operators to threshold spectral indices, combining the thresholds with `And()`:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Install Earth Engine API and geemap\n",
    "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n",
    "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n",
    "\n",
    "**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Installs geemap package\n",
    "import subprocess\n",
    "\n",
    "try:\n",
    "    import geemap\n",
    "except ImportError:\n",
    "    print('geemap package not installed. Installing ...')\n",
    "    subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n",
    "\n",
    "# Checks whether this notebook is running on Google Colab\n",
    "try:\n",
    "    import google.colab\n",
    "    import geemap.eefolium as emap\n",
    "except:\n",
    "    import geemap as emap\n",
    "\n",
    "# Authenticates and initializes Earth Engine\n",
    "import ee\n",
    "\n",
    "try:\n",
    "    ee.Initialize()\n",
    "except Exception as e:\n",
    "    ee.Authenticate()\n",
    "    ee.Initialize()  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create an interactive map \n",
    "The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = emap.Map(center=[40,-100], zoom=4)\n",
    "Map.add_basemap('ROADMAP') # Add Google Map\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add Earth Engine Python script "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Load a Landsat 8 image.\n",
    "image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318')\n",
    "\n",
    "# Create NDVI and NDWI spectral indices.\n",
    "ndvi = image.normalizedDifference(['B5', 'B4'])\n",
    "ndwi = image.normalizedDifference(['B3', 'B5'])\n",
    "\n",
    "# Create a binary layer using logical operations.\n",
    "bare = ndvi.lt(0.2).And(ndwi.lt(0))\n",
    "\n",
    "# Mask and display the binary layer.\n",
    "Map.setCenter(-122.3578, 37.7726, 12)\n",
    "Map.addLayer(bare.updateMask(bare), {}, 'bare')\n",
    "\n",
    "Map.addLayerControl()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As illustrated by this example, the output of relational and boolean operators is either True (1) or False (0). To mask the 0's, you can mask the resultant binary image with itself. \n",
    "\n",
    "The binary images that are returned by relational and boolean operators can be used with mathematical operators. This example creates zones of urbanization in a nighttime lights image using relational operators and `image.add()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = emap.Map()\n",
    "\n",
    "# Load a 2012 nightlights image.\n",
    "nl2012 = ee.Image('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS/F182012')\n",
    "lights = nl2012.select('stable_lights')\n",
    "Map.addLayer(lights, {}, 'Nighttime lights')\n",
    "\n",
    "# Define arbitrary thresholds on the 6-bit stable lights band.\n",
    "zones = lights.gt(30).add(lights.gt(55)).add(lights.gt(62))\n",
    "\n",
    "# Display the thresholded image as three distinct zones near Paris.\n",
    "palette = ['000000', '0000FF', '00FF00', 'FF0000']\n",
    "Map.setCenter(2.373, 48.8683, 8)\n",
    "Map.addLayer(zones, {'min': 0, 'max': 3, 'palette': palette}, 'development zones')\n",
    "\n",
    "Map.addLayerControl()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the code in the previous example is equivalent to using a [ternary operator](http://en.wikipedia.org/wiki/%3F:) implemented by `expression()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "Map = emap.Map()\n",
    "\n",
    "# Create zones using an expression, display.\n",
    "zonesExp = nl2012.expression(\n",
    "    \"(b('stable_lights') > 62) ? 3\" +\n",
    "      \": (b('stable_lights') > 55) ? 2\" +\n",
    "        \": (b('stable_lights') > 30) ? 1\" +\n",
    "          \": 0\"\n",
    ")\n",
    "Map.addLayer(zonesExp,\n",
    "             {'min': 0, 'max': 3, 'palette': palette},\n",
    "             'development zones (ternary)')\n",
    "Map.setCenter(2.373, 48.8683, 8)\n",
    "\n",
    "Map.addLayerControl()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Observe that in the previous expression example, the band of interest is referenced using the`b()` function, rather than a dictionary of variable names. (Learn more about image expressions on [this page](https://developers.google.com/earth-engine/image_math#expressions). Using either mathematical operators or an expression, the output is the same and should look something like Figure 2.\n",
    "\n",
    "Another way to implement conditional operations on images is with the `image.where()` operator. Consider the need to replace masked pixels with some other data. In the following example, cloudy pixels are replaced by pixels from a cloud-free image using `where()`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = emap.Map()\n",
    "\n",
    "# Load a cloudy Landsat 8 image.\n",
    "image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20130603')\n",
    "Map.addLayer(image,\n",
    "             {'bands': ['B5', 'B4', 'B3'], 'min': 0, 'max': 0.5},\n",
    "             'original image')\n",
    "\n",
    "# Load another image to replace the cloudy pixels.\n",
    "replacement = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20130416')\n",
    "\n",
    "# Compute a cloud score band.\n",
    "cloud = ee.Algorithms.Landsat.simpleCloudScore(image).select('cloud')\n",
    "\n",
    "# Set cloudy pixels to the other image.\n",
    "replaced = image.where(cloud.gt(10), replacement)\n",
    "\n",
    "# Display the result.\n",
    "Map.centerObject(image, 9)\n",
    "Map.addLayer(replaced,\n",
    "             {'bands': ['B5', 'B4', 'B3'], 'min': 0, 'max': 0.5},\n",
    "             'clouds replaced')\n",
    "\n",
    "Map.addLayerControl()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example, observe the use of the `simpleCloudScore()` algorithm. This algorithm ranks pixels by cloudiness on a scale of 0-100, with 100 most cloudy. Learn more about `simpleCloudScore()` on the [Landsat Algorithms page](https://developers.google.com/earth-engine/landsat#simple-cloud-score)."
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
